//
//  headCell.m
//  jiaKaoZhuShou
//
//  Created by 金艺社 on 2018/5/18.
//  Copyright © 2018年 金艺社. All rights reserved.
//

#import "headCell.h"
#import "myBillSuperVC.h"
#import "myBill.h"
#import "topUpVC.h"
@interface headCell () <UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (weak, nonatomic) IBOutlet UIButton *addMoney_btn;
@property (weak, nonatomic) IBOutlet UIButton *withdrawa_btn;
@property (weak, nonatomic) IBOutlet UIButton *giveMoney_btn;

@end
@implementation headCell

- (void)awakeFromNib {
    [super awakeFromNib];
    self.addMoney_btn.layer.masksToBounds = YES;
    self.addMoney_btn.layer.cornerRadius = 10;
    self.addMoney_btn.layer.borderColor = [UIColor whiteColor].CGColor;
    self.addMoney_btn.layer.borderWidth = 1;
    
    self.withdrawa_btn.layer.masksToBounds = YES;
    self.withdrawa_btn.layer.cornerRadius = 10;
    self.withdrawa_btn.layer.borderColor = [UIColor whiteColor].CGColor;
    self.withdrawa_btn.layer.borderWidth = 1;
    
    self.giveMoney_btn.layer.masksToBounds = YES;
    self.giveMoney_btn.layer.cornerRadius = 15;
    
    self.head_imgV.layer.masksToBounds = YES;
    self.head_imgV.layer.cornerRadius = 28.5;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}
- (IBAction)return_click:(id)sender {
    [[helpPublic getCurrentViewController:self].navigationController setNavigationBarHidden:NO];
    [[helpPublic getCurrentViewController:self].navigationController popViewControllerAnimated:NO];
}
- (IBAction)addMoneyClick:(id)sender {
    topUpVC *VC = [topUpVC new];
    VC.objectId = @"1";
    [[helpPublic getCurrentViewController:self].navigationController pushViewController:VC animated:YES];
}
- (IBAction)lessMoneyClick:(id)sender {
    topUpVC *VC = [topUpVC new];
    VC.objectId = @"2";
    [[helpPublic getCurrentViewController:self].navigationController pushViewController:VC animated:YES];
}
- (IBAction)ImmediateRepaymentClick:(id)sender {
    myBillSuperVC *VC = [myBillSuperVC new];
    [[helpPublic getCurrentViewController:self].navigationController pushViewController:VC animated:YES];
}
- (IBAction)uploadHeadImg_click:(id)sender {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //按钮：从相册选择，类型：UIAlertActionStyleDefault
    [alert addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //初始化UIImagePickerController
        UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
        //获取方式1：通过相册（呈现全部相册），UIImagePickerControllerSourceTypePhotoLibrary
        //获取方式2，通过相机，UIImagePickerControllerSourceTypeCamera
        //获取方法3，通过相册（呈现全部图片），UIImagePickerControllerSourceTypeSavedPhotosAlbum
        PickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //允许编辑，即放大裁剪
        PickerImage.allowsEditing = YES;
        //自代理
        PickerImage.delegate = self;
        //页面跳转
        [[helpPublic getCurrentViewController:self] presentViewController:PickerImage animated:YES completion:nil];
    }]];
    //按钮：拍照，类型：UIAlertActionStyleDefault
    [alert addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
        /**
         其实和从相册选择一样，只是获取方式不同，前面是通过相册，而现在，我们要通过相机的方式
         */
        UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
        //获取方式:通过相机
        PickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
        PickerImage.allowsEditing = YES;
        PickerImage.delegate = self;
        [[helpPublic getCurrentViewController:sender] presentViewController:PickerImage animated:YES completion:nil];
    }]];
    //按钮：取消，类型：UIAlertActionStyleCancel
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [[helpPublic getCurrentViewController:self] presentViewController:alert animated:YES completion:nil];
}

- (void)setModel:(userCenterModel *)model  {
    _model = model;
    [self.head_imgV sd_setImageWithURL:[NSURL URLWithString:_model.headImg] placeholderImage:[UIImage imageNamed:@"headPortrait"]];
    self.userPhone_lab.text = _model.userName;
    self.balanceMoney_lab.text = [NSString stringWithFormat:@"%@元", _model.account];
    self.nextReturn_lab.text = _model.shouldRepayment;
    self.total_lab.text = _model.total;
}

//PickerImage完成后的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    //创建通知
    NSNotification *notification =[NSNotification notificationWithName:@"headImg" object:nil];
    //通过通知中心发送通知
    [[NSNotificationCenter defaultCenter] postNotification:notification];
    //定义一个newPhoto，用来存放我们选择的图片。
    UIImage *newPhoto = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    [[helpPublic getCurrentViewController:self] dismissViewControllerAnimated:YES completion:nil];
    [self uploadHeadImage:newPhoto];
}
- (void)uploadHeadImage:(UIImage *)img
{
    //截取图片
    NSData *imageData = UIImageJPEGRepresentation(img , 0.01);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
    // 参数
    NSDictionary *parames = @{@"token":USERTOKEN};
    // 访问路径
    NSString *stringURL = [[apiManger shareApiManger] uploadHead];
    [manager POST:stringURL parameters:parames constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        // 上传文件
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat            = @"yyyyMMddHHmmss";
        NSString *str                   = [formatter stringFromDate:[NSDate date]];
        NSString *fileName              = [NSString stringWithFormat:@"%@.png", str];
        [formData appendPartWithFileData:imageData name:@"imgFile" fileName:fileName mimeType:@"image/png"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD gk_toastShowMessage:@"上传成功"];
        [self.head_imgV sd_setImageWithURL:[NSURL URLWithString:responseObject[@"fullUrl"]] placeholderImage:[UIImage imageNamed:@"headPortrait"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            NSLog(@"load complete!");
        }];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD gk_toastShowMessage:@"上传失败"];
    }];
}
//点击相册的取消按钮
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}
@end
